package com.zuo.seckilldemo.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.zuo.seckilldemo.entity.Order;
import com.zuo.seckilldemo.entity.SeckillMessage;
import com.zuo.seckilldemo.entity.User;
import com.zuo.seckilldemo.service.GoodsService;
import com.zuo.seckilldemo.service.OrderInfoService;
import com.zuo.seckilldemo.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class MQReceiver {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsService goodsService;
    @RabbitListener(queues = "seckillQueue")
    public void receive(String msg){
        log.info("接收消息"+msg);
        SeckillMessage seckillMessage = JSON.parseObject(msg, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodId = seckillMessage.getGoodId();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        if (goodsVo.getStockCount()<1) return;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Order order = (Order) valueOperations.get("userId:" + user.getId() + "_goodsId:" + goodId);
        if (order!=null){
            return;
        }
        orderInfoService.seckill(user,goodsVo);

    }
}
